/*
repository.go 领域层
*/

package user

import (
	"context"
	"wire/internal/database"
)

type User struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
}

type Repository interface {
	CreateUser(ctx context.Context, user *User) error
	GetUser(ctx context.Context, id int) (*User, error)
	ListUsers(ctx context.Context) ([]*User, error)
	UpdateUser(ctx context.Context, user *User) error
	DeleteUser(ctx context.Context, id int) error
}

type repository struct {
	db *database.DB
}

// CreateUser implements Repository.
func (r *repository) CreateUser(ctx context.Context, user *User) error {
	_, err := r.db.ExecContext(ctx,
		"INSERT INTO users (name, email) values (?,?)",
		user.Name, user.Email)
	return err
}

// DeleteUser implements Repository.
func (r *repository) DeleteUser(ctx context.Context, id int) error {
	_, err := r.db.ExecContext(ctx, "DELETE FROM users WHERE id = ?", id)
	return err
}

// GetUser implements Repository.
func (r *repository) GetUser(ctx context.Context, id int) (*User, error) {
	user := &User{}
	err := r.db.QueryRowContext(ctx,
		"SELECT id, name, email FROM users WHERE id = ?", id).
		Scan(&user.ID, &user.Name, &user.Email)
	if err != nil {
		return nil, err
	}
	return user, nil
}

// ListUsers implements Repository.
func (r *repository) ListUsers(ctx context.Context) ([]*User, error) {
	// 简化实现
	return []*User{}, nil
}

// UpdateUser implements Repository.
func (r *repository) UpdateUser(ctx context.Context, user *User) error {
	_, err := r.db.ExecContext(ctx,
		"UPDATE users SET name = ?, email = ? WHERE id = ?",
		user.Name, user.Email, user.ID)
	return err
}

func NewRepository(db *database.DB) Repository {
	return &repository{db: db}
}
